home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16766 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
  2. From: ian.johnston@ubs.com (Ian Johnston (by ubsswop))
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Friend vs. Member function for operator overload
  5. Date: 12 Apr 1996 07:57:19 GMT
  6. Organization: UBS
  7. Distribution: world
  8. Message-ID: <4kl2cv$bpm@ubszh.fh.zh.ubs.com>
  9. References: <4kj55n$mv2@homenet.hom.net>
  10. NNTP-Posting-Host: nol2179.fh.zh.ubs.com
  11.  
  12. In article <4kj55n$mv2@homenet.hom.net>, dengel@hom.net (Daniel P. Engel III) writes:
  13. |> Can anyone tell me the relative advantages and disadvantages of using
  14. |> a friend function vs. a member function to overload an operator, such
  15. |> as addition?  For example, suppose you have a Complex class (I'm not
  16. |> interested in building a complex class--I'm just using this for an
  17. |> example.):
  18.  
  19. [...]
  20.  
  21. |> Can anyone tell me if one of these the "preferred" way of doing it?
  22. |> And, what are the advantages and disadvantages of each?
  23.  
  24. When the operator + is a member of the class, the left hand argument
  25. must be a class member:
  26.  
  27.     x = aComplex + aDouble;        // Works
  28.     x = aDouble + aComplex;        // Doesnt work
  29.                     // (or at least, doesnt
  30.                     //  use Complex::operator +())
  31.  
  32. When the operator + is a friend, you can define a version where the
  33. lhs is a class object, and a version where the lhs is a builtin. Then:
  34.  
  35.     x = aComplex + aDouble;        // operator + (Complex const &, double)
  36.     x = aDouble + aComplex;        // operator + (double, Complex const &)
  37.  
  38.  
  39. Personally, I prefer the friend functions for this reason.
  40.  
  41. Ian
  42.